import { Component } from '@angular/core';
import { NavController,LoadingController,AlertController,Platform } from 'ionic-angular';
import {  Http } from '@angular/http';
declare var window;
declare const baidumap_location: any; 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
})
export class HomePage  {
  public updateText='正在下载更新包';
  public showUpdate:boolean=false;
  public interval:any;
  public url:any;
  constructor(
    public navCtrl: NavController,
    public loadingCtrl:LoadingController,
    public alertCtrl:AlertController,
    public http:Http,
    public platform: Platform) {
     
      window['cordova'].ThemeableBrowser.open('http://apache.org','_blank', {

        statusbar: {
     
            color: '#f8f8f8'
     
        },
     
        toolbar: {
     
            height:44,
     
            color: '#f8f8f8'
     
        },
     
        title: {
            color: '#000',
            staticText:'测试中',
            showPageTitle: false
        },
     
        backButton: {
     
            image: 'back',
     
            imagePressed: 'back_pressed',
     
            align: 'left',
     
            event: 'backPressed'
     
        },
     
        forwardButton: {
     
            image: 'forward',
     
            imagePressed: 'forward_pressed',
     
            align: 'left',
     
            event: 'forwardPressed'
     
        },
     
        closeButton: {
     
            image: 'close',
     
            imagePressed: 'close_pressed',
     
            align: 'left',
     
            event: 'closePressed'
     
        },
     
        customButtons: [
     
            {
     
                image: 'share',
     
                imagePressed: 'share_pressed',
     
                align: 'right',
     
                event: 'sharePressed'
     
            }
     
        ],
     
        menu: {
     
            image: 'menu',
     
            imagePressed: 'menu_pressed',
     
            title: 'Test',
     
            cancel: 'Cancel',
     
            align: 'right',
     
            items: [
     
                {
     
                     event: 'helloPressed',
     
                     label: 'Hello World!'
     
                },
     
                {
     
                     event: 'testPressed',
     
                     label: 'Test!'
     
                }
     
            ]
     
        },
     
        backButtonCanClose: true
     
     }).addEventListener('backPressed',function(e) {
     
        alert('back pressed');
     
     }).addEventListener('helloPressed',function(e) {
     
        alert('hello pressed');
     
     }).addEventListener('sharePressed',function(e) {
     
        alert(e.url);
     
     }).addEventListener(window['cordova'].ThemeableBrowser.EVT_ERR,function(e) {
     
        console.error(e.message);
     
     }).addEventListener(window['cordova'].ThemeableBrowser.EVT_WRN,function(e) {
     
        console.log(e.message);
     
     });
  }

  onShowUpdate(){
    this.showUpdate=true;
  }
  hiddenUpdate(){
    this.showUpdate=false;
  }
  //内壳外壳，更新
  initialize() {
    this.bindEvents();
  }
  bindEvents() {
    document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    //当插件无法从服务器加载更新时发送。错误详细信息附加到事件。用于外壳更新
    document.addEventListener('chcp_updateLoadFailed', this.onUpdateLoadError.bind(this), false);
    //当新版本成功加载并准备安装时发送
    document.addEventListener('chcp_updateIsReadyToInstall', this.onReadyToInstall.bind(this), false);
    //在即将安装更新时发送。
    document.addEventListener('chcp_beforeInstall', this.onBeforeInstall.bind(this), false);
    //成功安装更新
    document.addEventListener('chcp_updateInstalled', this.onInstalle.bind(this), false);
    //安装更新失败时
    document.addEventListener('chcp_updateInstallFailed', this.installError.bind(this), false);
    //当用户手机存储卡不够用时
    document.addEventListener('chcp_assetsInstallationError', this.onInstallationError.bind(this), false);
  }

  // deviceready Event Handler
  onDeviceReady() {


    window.chcp.getVersionInfo((error,data)=>{
      if(error){
       alert(error)
      }
     alert(data.currentWebVersion);
      let currentWebVersion = data.currentWebVersion;
      let release;
      debugger

    });
    
  }
  installError(){
   alert('安装更新失败')
  }
  installationCallback(error) {
    if (error) {
      //console.log('Failed to install the update with error code: ' + error.code);
      //console.log(error.description);
          let alert = this.alertCtrl.create({
          title: '更新不成功',
          message: '安装更新包过程中发生错误，请重启app再次尝试升级',
          buttons: [
            {
              text: '明白了',
              role: 'cancel',
              handler: () => {}
            }
          ]
        });
        alert.present();
      
    } else {
     alert('Update installed!');
    }
  }

  fetchUpdateCallback(error, data ) {
     alert('发生错误，错误代码: ' + error.code);
      if(error.code===-3 || error.code===-4){
            this.hiddenUpdate();
            window.clearInterval()
            var dialogMessage = '下载失败，去App store下载最新版';
            window.chcp.requestApplicationUpdate(dialogMessage);
      }
      //alert(error.description);
      //error.code=2没有更新，error.code=-17下载正在进行
      if(error){
          //loading.dismiss();
          //console.log('没有检测到任何文件更新')
          //console.log(error.description);
          
          this.hiddenUpdate();
          setTimeout(()=>{
            window.clearInterval(this.interval)
          },100)
          
      }
       alert('文件加载中');
      
      
  }
  //外壳更新
  onUpdateLoadError(eventData) {
    var error = eventData.detail.error;
    if (error && error.code == window.chcp.error.APPLICATION_BUILD_VERSION_TOO_LOW) {
        //console.log('Native side update required');
        var dialogMessage = '发现新版本，即刻下载安装.';
        window.chcp.requestApplicationUpdate(dialogMessage);
    }
  }
  userWentToStoreCallback() {}
  userDeclinedRedirectCallback() {}
  //当新版本成功加载并准备安装时发送
  onReadyToInstall(){
    //console.log('正在安装更新');
    this.updateText = '正在安装更新'
    window.chcp.installUpdate(this.installationCallback.bind(this));
  }
  //安装即将开始
  onBeforeInstall(){
    this.updateText = '即将开始升级'
  }
  //安装更新成功
  onInstalle(){
    //console.log('升级完成')
    this.updateText = '升级完成'
    this.hiddenUpdate();
    setTimeout(()=>{
      window.clearInterval(this.interval)
    },100)
  }
  //存储卡不够用时提醒用户
  onInstallationError(){
    //console.log('存储空间不够升级')
    let alert = this.alertCtrl.create({
      title: '存储错误',
      message: '您的手机存储不足，无法下载更新包',
      buttons: [
        {
          text: '明白了',
          role: 'cancel',
          handler: () => {}
        }
      ]
    });
    alert.present();
  }

}